package org.jvnc.rfb.state;

/**
* <br><br><center><table border="1" width="80%"><hr>
* <p>
* Copyright (C) 2006-2007 by Deon Wu
* <p>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.0
* of the License, or (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* <a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html">GNU Lesser General Public License</a>
* for more details.
* <p>
* You should have received a copy of the <a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html">
* GNU Lesser General Public License</a> along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* <hr></table></center>
* **/

import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;

import org.jvnc.logging.VLog;
import org.jvnc.rfb.RFBSocketClient;
import org.jvnc.rfb.event.RfbEvent;
import org.jvnc.rfb.event.VersionEvent;

public class InitProtocolVersion extends AbstractStateHandle{
	private boolean readed;
	private static VLog log = VLog.getLog();
	private String version  = null;
	
	public InitProtocolVersion(){
		readed = false;
	}

	/**
	 * 在协议初始阶段，分为两步处理。先服务端的协议版本，再发送客户端的版本。
	 * @throws IOException 
	 */
	public RfbEvent process() throws IOException {
		RfbEvent event = null;
		if(!readed){
			event = readInitVersion();
			readed = true;
		}else{
			event = writeInitVersion(); 
			//改变socket 进入下一个状态。(安全连接的处理)
			socket.changeState(new AuthenicationProtocol());
		}
		
		return event;
	}
	
	/**
	 * 读取服务器端的初始化协议版本。触发VersionEvnet事件。 
	 * @return
	 */
	private RfbEvent readInitVersion() throws IOException{

        byte[] b = new byte[12];
        socket.getInputStream().readFully( b );
        version = new String( b );
        
        log.info("Sever Version:" + version);
        
        //Fix me
        if(!version.equals("RFB 003.008\n")){
        	log.debug("The Server Version not supported!");	
        	socket.changeState(new CloseConnection());
        }
        
		return new VersionEvent(socket,version);
	}

	/**
	 * 发送本地初始化协议版本。不会产生事件。 
	 * @return
	 */
	private RfbEvent writeInitVersion() throws IOException{
		String initVersion = socket.getProtocoVersion();
		DataOutput out = socket.getOutputStream();
		
		if(initVersion == null){
			initVersion = this.version;
		}
		
		log.debug("Client Response Version:" + initVersion);

		out.write(initVersion.getBytes());
		
		if(!initVersion.endsWith("\n")){
			out.writeBytes("\n");
		}

		return null;
	}

}
